<template>
  
  <el-dialog
    title="上传文件"
    @close="closeHandle"
    :visible.sync="visible">
    <el-upload
      drag
      :headers="headers"
      :action="url"
      :before-upload="beforeAvatarUpload"
      :on-success="successHandle"
      multiple
      :file-list="fileList"
      style="text-align: center;">
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只支持jpg、png、gif格式的图片！</div>
    </el-upload>
  </el-dialog>
</template>

<script>
import * as imageConversion from 'image-conversion';
  export default {
    data () {
      return {
        visible: false,
        url: '',
        num: 0,
        successNum: 0,
        fileList: [],
        headers:{}
      }
    },
    props: [
       'uploadList',
    ],
    methods: {
      beforeAvatarUpload(file) {
　　　　　const isJpgOrPng = file.type !== 'image/jpg' || file.type !== 'image/jpeg' || file.type !== 'image/png' || file.type !== 'image/gif';
　　　　　// 这里判断图片格式是否为jpeg或png   看实际情况使用
　　　　　if (!isJpgOrPng) {
　　　　　　　this.$message.error('只支持jpg、png、gif格式的图片！')
　　　　　　　return false;
　　　　　}
         const isLtM = file.size / 1024 / 1024 >= 0.45 // 这里对于大于 1M 的图片都进行压缩处理
　　　　　// 使用 Promise()防止没处理文件就上传
        return new Promise((resolve) => {
          // 小于1M 不压缩
          if (!isLtM) {
            resolve(file)
          }
          // 压缩到400KB,这里的400就是要压缩的大小,可自定义
          imageConversion.compressAccurately(file, 400).then((res) => {
            resolve(res)
          })
          //compressAccurately有多个参数时传入对象
          //imageConversion.compressAccurately(file, {
          // size: 1024, //图片大小压缩到1024kb
          // width:1280 //宽度压缩到1280
          //}).then(res => {
          //resolve(res)
          //})
        })
      },
      init (id) {
        this.headers={
          token:this.$cookie.get('token'),
          'timestamp': new Date().getTime(),
          sign:'111',
        }
        this.url = this.$http.adornUrl(`/common/file/upload`)
        console.log(this.url)
        this.visible = true
      },
      // 上传成功
      successHandle (response, file, fileList) {
        // console.log(file)
        this.fileList = fileList
        this.successNum++
        if (response && response.code ==="200") {
            // console.log(response.data)
           this.uploadList(response.data)
           this.visible = false
        } else {
          this.$message.error(response.msg)
        }
      },
      // 弹窗关闭时
      closeHandle () {
        this.fileList = []
        // this.$emit('refreshDataList')
      }
    }
  }
</script>
